package simple

import (
	"fmt"
	"net"
	"net/http"
	"time"
)

func Start() {
	s := &HttpServer{}
	var rootHandler HandlerFunc = func(context *Context) {
		fmt.Println("root")
		time.Sleep(time.Second)
	}
	s.AddRoute(http.MethodGet, "/", rootHandler)
	h1 := func(context *Context) {
		fmt.Println("root")
		time.Sleep(time.Second)
	}
	s.Post("/h1", h1)

	h21 := func(context *Context) {
		fmt.Println("root")
		time.Sleep(time.Second)
	}
	h22 := func(context *Context) {
		fmt.Println("root")
		time.Sleep(time.Second)
	}
	s.Get("h2", func(context *Context) {
		h21(context)
		h22(context)
	})

	_ = s.Start(":8001")
}

type Context struct {
	req        *http.Request
	respWriter http.ResponseWriter
}

type HandlerFunc func(*Context)

type Server interface {
	http.Handler
	Start(addr string) error
	AddRoute(method string, path string, handler HandlerFunc)
}

type HttpServer struct {
}

func (m *HttpServer) AddRoute(method, path string, handler HandlerFunc) {

}

func (m *HttpServer) Get(path string, handler HandlerFunc) {
	m.AddRoute(http.MethodGet, path, handler)
}

func (m *HttpServer) Post(path string, handler HandlerFunc) {
	m.AddRoute(http.MethodPost, path, handler)
}

func (m *HttpServer) Start(addr string) error {
	//// 阻塞，启动前可以加hook
	//return http.ListenAndServe(addr, m)

	// 非阻塞，启动前加hook
	fmt.Println("Starting...")
	listener, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}
	// 启动后加hook
	fmt.Println("Started")
	return http.Serve(listener, m)

}

func (m *HttpServer) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	ctx := &Context{req: request, respWriter: writer}
	m.serve(ctx)
}

func (m *HttpServer) serve(ctx *Context) {
	_, _ = ctx.respWriter.Write([]byte("hello world, again"))
}

type HttpsServerV2 struct {
	Server
	key  string
	cert string
}

func (s *HttpsServerV2) Start(addr string) error {
	return http.ListenAndServeTLS(addr, s.cert, s.key, s)
}
